package com.hlf.modules.merchant.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.hlf.common.constants.Constants;
import com.hlf.common.constants.FileConstants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.*;
import com.hlf.modules.merchant.bank.entity.BankCard;
import com.hlf.modules.merchant.bank.mapper.BankCardMapper;
import com.hlf.modules.merchant.goods.entity.Goods;
import com.hlf.modules.merchant.goods.entity.GoodsType;
import com.hlf.modules.merchant.goods.mapper.GoodsMapper;
import com.hlf.modules.merchant.goods.mapper.GoodsTypeMapper;
import com.hlf.modules.merchant.merchant.entity.Merchant;
import com.hlf.modules.merchant.merchant.service.MerchantService;
import com.hlf.modules.merchant.store.entity.Store;
import com.hlf.modules.merchant.store.mapper.StoreMapper;
import com.hlf.modules.merchant.store.service.StoreService;
import com.hlf.modules.sys.entity.File;
import com.hlf.modules.sys.entity.SysUserEntity;
import com.hlf.modules.sys.mapper.AreaMapper;
import com.hlf.modules.sys.mapper.SysUserMapper;
import com.hlf.modules.sys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("storeService")
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private GoodsTypeMapper goodsTypeMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private BankCardMapper bankCardMapper;
    @Autowired
    private PropertieUtil propertieUtil;

    /**
     * 查询单个店铺
     *
     * @param id
     * @return
     */
    @Override
    public Store queryObject(Long id) {
        return storeMapper.queryObject(id);
    }

    @Override
    public List<Store> queryList(Map<String, Object> map) {
        return storeMapper.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return storeMapper.queryTotal(map);
    }

    /**
     * 插入非空
     * 创建店铺,默认创建 商品类型分类
     *
     * @param store
     */
    @Transactional
    @Override
    public String saveStore(Store store) {
        //返回判断
        String flag = null;
        //保存门店
        storeMapper.insertSelective(store);

        //创建默认商品类型
        GoodsType goodsType = new GoodsType();
        goodsType.setStoreId(store.getId());
        goodsType.setInsertBy(store.getInsertBy());
        String[] goodsTypes = {"招牌菜", "凉菜", "热菜", "饮料"};
        for (String type : goodsTypes) {
            goodsType.setId(IdWorkerFactory.nextId());
            goodsType.setName(type);
            goodsTypeMapper.insertSelective(goodsType);
        }

        //创建茶位费
        Integer defaultTeaPrice = Constants.DEFAULT_TEA_PRICE;
        Goods goods = new Goods();
        goods.setId(IdWorkerFactory.nextId());
        goods.setMerchantId(store.getMerchantId());
        goods.setStoreId(store.getId());
        goods.setName("茶位费");
        goods.setGoodsType(Constants.DEFAULT_TEA_GOODS_TYPE);
        goods.setNum(IdWorkerFactory.nextId());
        goods.setSellPrice(defaultTeaPrice);
        //茶位费库存
        goods.setInitQty(99999);
        goods.setRemainQty(99999);
        goods.setInsertBy(store.getUserId());
        goods.setDailyStock(Constants.GOODS_DAILY_STOCK_OPEN);

        goodsMapper.insertSelective(goods);

        //user表填充storeId
        Long id = store.getId();
        Long userId = store.getUserId();

        if (userId == null) {
            throw new BusinessException("userId为空!");
        }

        SysUserEntity sysUserEntity = sysUserMapper.queryObject(userId);
        String storeIdStr = String.valueOf(id);
        String currentStoreId = sysUserEntity.getCurrentStoreId();
        if (currentStoreId == null || currentStoreId.length() == 0) {
            //修改当前门店id
            sysUserEntity.setCurrentStoreId(storeIdStr);
            //修改返回标志位
            flag = storeIdStr;
        }
        String storeIds = sysUserEntity.getStoreIds();

        //拼接
        if (storeIds == null || storeIds.length() == 0) {
            storeIds = storeIdStr + "/";
        } else {
            storeIds = storeIds + storeIdStr + "/";
        }
        sysUserEntity.setStoreIds(storeIds);
        //执行修改
        sysUserMapper.updateByPrimaryKeySelective(sysUserEntity);

        //返回标志位
        return flag;
    }

    /**
     * 创建门店
     *
     * @param merchantId
     * @param storeName
     * @param bizTypeId
     * @param province
     * @param city
     * @param district
     * @param address
     * @param cellphone
     * @param logoImgFilesJson
     * @return
     */
    @Transactional
    @Override
    public ReturnResult createStore(String merchantId, String storeName, String bizTypeId, String province, String city,
                                    String district, String address, String cellphone, String logoImgFilesJson) {

        Merchant merchant = merchantService.queryObject(Long.parseLong(merchantId));
        Long userId = merchant.getUserId(); //获取userId
        long id = IdWorkerFactory.nextId();
        //保存图片
        List<File> goodsImgs;
        if (logoImgFilesJson != null && logoImgFilesJson.length() > 0) {
            try {
                goodsImgs = JSON.parseArray(logoImgFilesJson, File.class);
            }catch (Exception e){
                throw new BusinessException("图片参数有误!");
            }
            for (File goodsImg : goodsImgs) {
                goodsImg.setInsertBy(userId);
                goodsImg.setForeignId(id);
            }
            fileService.inserts(goodsImgs);
        }
        Store store = new Store();
        store.setId(id);
        store.setUserId(userId);
        store.setName(storeName);
        store.setTelephone(cellphone);
        store.setMerchantId(Long.parseLong(merchantId));
        store.setSoftwareStatus(Constants.SOFTWARE_PAY_STATUS_TRY);
        store.setExpiryDate(DateUtil.addDay(new Date(), Integer.parseInt(propertieUtil.getPropertie("SOFT_FREE_DAYS"))));

        //生成地址
        store = buildAddress(store, province, city, district, address);
        //保存店铺
        String storeId = saveStore(store);

        //注册时创建店铺,返回storeId
        if (storeId != null && storeId.length() > 0) {
            Map<Object, Object> map = new HashMap<>();
            map.put("storeId", storeId);
            return ReturnResult.ok().put(Constants.DEFAULT_RESULT_NAME,map);
        }
        return ReturnResult.ok();
    }

    /**
     * 拼接地址
     *
     * @param store
     * @param province
     * @param city
     * @param district
     * @param address
     * @return
     */
    private Store buildAddress(Store store, String province, String city, String district, String address) {
        String provinceStr = null;
        String cityStr = null;
        String districtStr = null;
        if (province != null && province.length() > 0) {
            long pCode = Long.parseLong(province);
            store.setProvince(pCode);
            provinceStr = areaMapper.selectByAreaCode(pCode).getName();
        }
        if (city != null && city.length() > 0) {
            long cCode = Long.parseLong(city);
            store.setCity(cCode);
            cityStr = areaMapper.selectByAreaCode(cCode).getName();
        }
        if (district != null && district.length() > 0) {
            long dCode = Long.parseLong(district);
            store.setDistrict(dCode);
            districtStr = areaMapper.selectByAreaCode(dCode).getName();
        }
        //详细地址
        address = provinceStr + cityStr + districtStr + address;
        store.setAddress(address);
        return store;
    }

    /**
     * 门店列表
     *
     * @param
     * @return
     */
    @Override
    public List<Store> queryListForMerchantId(Long merchantId) {
        return storeMapper.queryListForMerchantId(merchantId);
    }

    /**
     * 修改门店信息
     *
     * @param user
     * @param name
     * @param province
     * @param city
     * @param district
     * @param address
     */
    @Override
    public void updateInfo(SysUserEntity user, String name, String province, String city, String district, String address) {

        Store store = new Store();
        Long userId = user.getUserId();
        String storeId = user.getCurrentStoreId();
        store.setId(Long.parseLong(storeId));
        store.setLastUpdateBy(userId);
        store.setName(name);
        store = buildAddress(store, province, city, district, address);

        int i = storeMapper.updateByPrimaryKeySelective(store);
        if (i == 0) {
            throw new BusinessException("修改失败!");
        }
    }

    /**
     * 上传门店形象照片
     *
     * @param user
     * @param storeImgFilesJson
     */
    @Override
    public void uploadStore(SysUserEntity user, String storeImgFilesJson) {
        Long userId = user.getUserId();
        String storeId = user.getCurrentStoreId();
        //保存图片
        List<File> storeImgs;
        if (storeImgFilesJson != null && storeImgFilesJson.length() > 0) {
            storeImgs = JSON.parseArray(storeImgFilesJson, File.class);

            //校验门店形象照数量
            List<File> files = fileService.select(FileConstants.STORE_IMG, Long.parseLong(storeId));
            int i = files.size() + storeImgs.size();
            if (i > Integer.valueOf(propertieUtil.getPropertie("STORE_IMG_NUMBER"))) {
                throw new BusinessException("照片数量过多!");
            }
            for (File storeImg : storeImgs) {
                storeImg.setInsertBy(userId);
                storeImg.setForeignId(Long.parseLong(storeId));
            }
            fileService.inserts(storeImgs);
        }
    }

    /**
     * 保存门店认证信息
     */
    @Override
    @Transactional
    public void saveStoreDetail(SysUserEntity user, String merchantName, String legalPerson, String identityCardImgJson,
                                String businessImg, String qsImg, String license, String accountName, String province, String city,
                                String district, String bankName, String branchBankName, String cardNo, String branchBankId,
                                String type, String openAccountLicenseImg) {
        Long profitBankCardId = IdWorkerFactory.nextId();
        Long userId = user.getUserId();
        Long storeId = Long.parseLong(user.getCurrentStoreId());

        Store storeQuery = storeMapper.queryObject(storeId);
        Byte auditStatus = storeQuery.getAuditStatus();
        if (Constants.AUDIT_STATUS_PASS.equals(auditStatus)){
            throw new BusinessException("审核已通过!");
        }
        Store store = new Store();
        store.setLastUpdateBy(userId);
        store.setId(storeId);
        store.setMerchantName(merchantName);
        store.setLegalperson(legalPerson);
        store.setLicense(license);
        store.setAuditStatus(Constants.AUDIT_STATUS_REVIEW);
        store.setProfitBankCardId(profitBankCardId);

        int j = storeMapper.updateByPrimaryKeySelective(store);
        if (j == 0){
            throw new BusinessException("认证失败!");
        }
        //保存身份证照片
        saveImg(storeId, userId, identityCardImgJson);
        //保存营业执照
        saveImg(storeId, userId, businessImg);
        //保存食品经营许可证照片
        saveImg(storeId, userId, qsImg);
        //保存开户许可证
        saveImg(storeId,userId,openAccountLicenseImg);
        //银行卡信息
        BankCard bankCard = new BankCard();
        bankCard.setId(profitBankCardId);
        bankCard.setUserId(userId);
        bankCard.setStoreId(storeId);
        bankCard.setBranchBankId(Integer.valueOf(branchBankId));  //支行id
        bankCard.setProvince(Long.parseLong(province));
        bankCard.setCity(Long.parseLong(city));
        bankCard.setDistrict(Long.parseLong(district));
        bankCard.setBankName(bankName);
        bankCard.setBranchBankName(branchBankName);
        bankCard.setCardNo(cardNo);
        bankCard.setAccountName(accountName);
        bankCard.setType(Integer.valueOf(type));
        bankCard.setInsertBy(userId);
        bankCard.setLastUpdateBy(userId);
        int i = bankCardMapper.insertSelective(bankCard);
        if (i == 0 ){
            throw new BusinessException("认证失败!");
        }
    }

    /**
     * 门店形象
     * @param user
     * @return
     */
    @Override
    public ReturnResult storeImg(SysUserEntity user) {
        List<File> fileList = fileService.select(FileConstants.STORE_IMG, Long.parseLong(user.getCurrentStoreId()));
        return ReturnResult.ok().put(Constants.DEFAULT_RESULT_NAME,fileList);
    }

    @Override
    public void update(Store store) {
        storeMapper.updateByPrimaryKeySelective(store);
    }

    @Override
    public void save(Store store) {
        storeMapper.save(store);
    }

    @Override
    public void delete(Long id) {
        storeMapper.delete(id);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        storeMapper.deleteBatch(ids);
    }

    /**
     * 分页查询
     */
    @Override
    public PageUtils queryListForPage(Map<String, Object> map) {
        Query query = new Query(map);
        int total = storeMapper.queryTotal(query);
        List<Store> storeList = null;
        if (total > 0) {
            storeList = storeMapper.queryList(query);
        }
        return new PageUtils(storeList, total, query.getLimit(), query.getPage());
    }

    /**
     * 根据当前门店高管userId查店铺
     *
     * @param userId
     * @return
     */
    @Override
    public Store queryObjectForUserId(Long userId) {
        return storeMapper.queryObjectForUserId(userId);
    }

    /**
     * 保存图片
     */
    public void saveImg(Long foreignId, Long userId, String imgsJson) {
        //保存图片
        List<File> imgList;
        if (imgsJson != null && imgsJson.length() > 0) {
            imgList = JSON.parseArray(imgsJson, File.class);
            for (File img : imgList) {
                img.setInsertBy(userId);
                img.setForeignId(foreignId);
            }
            fileService.inserts(imgList);
        }
    }


}
